package com.kmvc.message.activity;

import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.kmvc.message.R;
import com.kmvc.message.adapter.GroupAdapter;
import com.kmvc.message.database.DbHelper;
import com.kmvc.message.encryption.Encryption;
import com.kmvc.message.entity.StringEntity;
import com.kmvc.message.handler.StringHandler;
import com.kmvc.message.tools.WebService;
import com.kmvc.message.widget.PullToRefreshView;
import com.kmvc.message.widget.PullToRefreshView.OnFooterRefreshListener;
import com.kmvc.message.widget.PullToRefreshView.OnHeaderRefreshListener;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class MessageList extends Activity implements OnHeaderRefreshListener,
		OnFooterRefreshListener {
	// private MessageApplication application = null;
	int flag = -1;
	ListView lvListView;
	private PullToRefreshView mPullToRefreshView;

	private String message, area, datesString, key = "";
	AlertDialog.Builder builder;
	AlertDialog al;

	private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> showlist = new ArrayList<Map<String, Object>>();
	GroupAdapter adapter;
	private List<StringEntity> mStringList = new ArrayList<StringEntity>();

	private ProgressDialog progress;
	private Handler h = new Handler();
	Runnable r = new Runnable() {
		public void run() {
			DbHelper dbHelper = new DbHelper(getActivity());
			try {
				dbHelper.inserthistorybyListnew(mStringList);
				// endDate = new Date();
				// Log.e("写入数据库", (endDate.getTime() - beginDate.getTime()) /
				// 1000
				// + "S");
			} catch (Exception e) {
				e.printStackTrace();
				Log.e("SampleListFragement", e.toString());

			}
			dbHelper.close();
			progress.dismiss();
			Toast.makeText(getActivity(), "刷新成功!", Toast.LENGTH_LONG).show();
			ShowData(key);
		}
	};

	int NoRead=0;
	public void onCreate(Bundle parmBundle) {
		super.onCreate(parmBundle);
		setContentView(R.layout.conversation_activity);
		TextView localTextView = (TextView) findViewById(R.id.title_name);
		localTextView.setText("消息");

		findViewById(R.id.rlTitleBtnRightLayout).setVisibility(0);
		TextView textView = (TextView) findViewById(R.id.ivTitleBtnRightText);
		
		textView.setText("刷新");
		textView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				RefshData();
			}
		});
		init();
	}

	@SuppressWarnings("deprecation")
	public void init() {
		// application = (MessageApplication) getActivity().getApplication();
		lvListView = (ListView) findViewById(android.R.id.list);
		lvListView.setDividerHeight(1);
		mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		mPullToRefreshView.setLastUpdated(new Date().toLocaleString());
	}

	@Override
	public void onResume() {
		super.onResume();
		// application.isRefsh = false;
		ShowData(key);
	}

	private void ShowData(final String key) {
		list.clear();
		list = (List<Map<String, Object>>) getGroupData(key);
		for (int i = 0; i < 20&&i<list.size(); i++) {// 开始显示20条数据
			try {
				showlist.add(list.get(i));
			} catch (Exception e) {
				e.toString();
			}
		}
		adapter = new GroupAdapter(getActivity(), showlist, key);
		lvListView.setAdapter(adapter);
		// setListAdapter(adapter);
		
		MainTab.SetNum(NoRead);
		
		lvListView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("deprecation")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(getActivity(),
						MessageShowActivity.class);
				try {
					area = list.get(position).get("area").toString();
					datesString = list.get(position).get("date").toString();
				} catch (Exception e) {

					area = "没有信息";
					datesString = e.toString();
				}

				try {

					int index = area.indexOf("(");
					if(index>-1)
					{
						intent.putExtra("area", area.substring(0, index));
					}
					else 
					{
						intent.putExtra("area", area);	
					}
				} catch (Exception e) {
					intent.putExtra("area", area);
				}
				intent.putExtra("datestring", datesString);
				
				TextView textView=(TextView)view.findViewById(R.id.unreadmsg);
				if(textView!=null)
				{
					
					textView.setBackgroundDrawable(null);
					textView.setVisibility(8);
					String Num=(String)textView.getText();
					int num=0;
					try 
					{
						num=Integer.parseInt(Num);						
					} 
					catch (Exception e) 
					{
						
					}
					if(num>0)
					{
						DbHelper dbHelper=new DbHelper(MessageList.this);
						int index = area.indexOf("(");
						if(index>-1)
						{
							dbHelper.updateReadState(area.substring(0, index), datesString);
						}
						else 
						{
							dbHelper.updateReadState(area, datesString);
						}
						NoRead=NoRead-num;
						dbHelper.close();
						MainTab.SetNum(NoRead);
					}
				}
				

				getActivity().startActivity(intent);
				// overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
				// getActivity().finish();
				// getActivity().overridePendingTransition(R.anim.zoomin,
				// R.anim.zoomout);
				getActivity().overridePendingTransition(R.anim.slide_left_in,
						R.anim.slide_left_out);

			}
		});

		lvListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					final int arg2, long arg3) {
				final AlertDialog.Builder Choicebuilder = new AlertDialog.Builder(
						getActivity());
				Choicebuilder.setCancelable(false);
				Choicebuilder
						.setTitle("选择操作")
						// .setIcon(icLauncher)
						.setSingleChoiceItems(
								new String[] { "删除当前会话", "删除全部会话" }, -1,
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										if (which == 0) {
											area = list.get(arg2).get("area")
													.toString();
											datesString = list.get(arg2)
													.get("date").toString();
											try {
												int index = area.indexOf("(");
												area = area.substring(0, index);

											} catch (Exception e) {
												e.toString();
											}
											flag = 0;
											// showMyDialog(
											// "删除" + area + "的所有会话?",
											// which);
										} else {
											flag = 1;
											// showMyDialog("删除全部会话", which);
										}

									}

								})
						.setNegativeButton("取消",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {

									}
								})
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										DbHelper db = new DbHelper(
												MessageList.this);
										if (flag == 0) {
											// db.deletebyid(id);
											db.delteall(area, datesString);
										}
										if (flag == 1) {
											db.deleteall();
										}
										Toast.makeText(getActivity(), "删除成功",
												Toast.LENGTH_LONG).show();
										ShowData(key);

									}
								});

				Choicebuilder.create();
				Choicebuilder.show();

				return false;
			}

		});

	}

	@SuppressLint("SimpleDateFormat")
	private List<Map<String, Object>> getGroupData(String key2) {
		list.clear();
		showlist.clear();
		DbHelper dbhelper = new DbHelper(getActivity());
		Cursor c = dbhelper.selectGroup(key2);
		NoRead=0;
		while (c.moveToNext()) {
			Map<String, Object> map = new HashMap<String, Object>();
			if (c.getString(c.getColumnIndex("count(id)")).equals("1")) {
				map.put("area", c.getString(c.getColumnIndex("area")));
			} else {
				map.put("area",
						c.getString(c.getColumnIndex("area")) + "("
								+ c.getString(c.getColumnIndex("count(id)"))
								+ ")");
			}
			
			map.put("date", c.getString(c.getColumnIndex("dates")));
			map.put("num", c.getString(c.getColumnIndex("num")));
			map.put("area1", c.getString(c.getColumnIndex("area")));
			map.put("IMG_URL2", c.getString(c.getColumnIndex("IMG_URL2")));
			String conString = c.getString(c.getColumnIndex("Content"));
			
			NoRead+=c.getInt(c.getColumnIndex("num"));
			
			if (conString.getBytes().length == conString.length()
					&& !conString.contains(".")) {
				try {
					conString = Encryption.decode(conString);
				} catch (Exception e) {

				}

			}
			if (conString.startsWith("<html>"))// 有html代码的
			{
				int titlestart = conString.indexOf("<title>") + 7;
				int titleend = conString.indexOf("</title>");

				try {
					String titleString = conString.substring(titlestart,
							titleend);
					map.put("content", titleString);
				} catch (Exception e) {
					//
					e.toString();
				}
			} else 
			{
				try 
				{
					if(conString.startsWith("<Image>")&&conString.endsWith("</Image>"))
					{
						map.put("content", "[图片]");
					}
					else 
					{
						map.put("content", conString.substring(0, 20));
					}
				} 
				catch (Exception e) 
				{
					//
					map.put("content", conString);
				}
			}

			list.add(map);
		}
		if (c.getCount() == 0) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ids", "-1");
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			Date newdate = new Date(System.currentTimeMillis());// 获取当前时间
			map.put("area", "信息通报");
			map.put("date", formatter.format(newdate));
			map.put("content", "暂时没有信息");
			list.add(map);
		}
		c.close();
		dbhelper.close();
		return list;

	}

	protected Activity getActivity() {
		return this;
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		// 上拉加载更多
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				ShowMoreData();
				adapter.notifyDataSetChanged();
				mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 500);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		RefshData();
		mPullToRefreshView.postDelayed(new Runnable() {
			@SuppressWarnings("deprecation")
			@Override
			public void run() {
				mPullToRefreshView.onHeaderRefreshComplete("更新于:"
						+ new Date().toLocaleString());
				mPullToRefreshView.onHeaderRefreshComplete();
			}

		}, 1000);

	}

	
	/**
	 * 模拟加载数据
	 */
	protected void ShowMoreData() {
		int count = adapter.getCount();
		for (int i = count; i < count + 20; i++) {
			try {
				adapter.addItem(list.get(i));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
	
	private void RefshData() {
		progress = ProgressDialog.show(getActivity(), "请稍候", "刷新数据中...", true);
		progress.setCancelable(true);
		final DbHelper dbhelper = new DbHelper(getActivity());
		final int messageCount = dbhelper.getTodayMessageCount();

		new Thread() {
			public void run() {

				try {
					TelephonyManager mTelephonyMgr = (TelephonyManager) getActivity()
							.getSystemService(Context.TELEPHONY_SERVICE);
					String IMSI = null;
					String MolNo = null;
					try {
						IMSI = mTelephonyMgr.getSubscriberId();
						MolNo = mTelephonyMgr.getDeviceId();
					} catch (Exception e) {
						e.printStackTrace();
					}
					final SharedPreferences settingSharedPreferences = getActivity()
							.getSharedPreferences("phonenumber", 0);
					String tempimsi = settingSharedPreferences.getString(
							"IMSI", "");
					String tempmolno = settingSharedPreferences.getString(
							"MolNo", "");
					if (IMSI.equals(tempimsi) && MolNo.equals(tempmolno)) {
						message = "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>"
								+ WebService.RefshCDMA(IMSI, MolNo,
										messageCount);
						if (!message
								.equals("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>null")
								&& !message
										.equals("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><data></data>")) {
							//Log.e("message", message.toString());
							// endDate = new Date();
							// Log.e("获取到数据",
							// (endDate.getTime() - beginDate.getTime())
							// / 1000 + "S");
							StringReader read = new StringReader(
									message.toString());
							InputSource mInputSource = new InputSource(read);
							try {
								SAXParserFactory msSaxParserFactory = SAXParserFactory
										.newInstance();
								SAXParser msSaxParser = msSaxParserFactory
										.newSAXParser();
								XMLReader msXmlReader = msSaxParser
										.getXMLReader();
								StringHandler mStringHandler = new StringHandler();
								msXmlReader.setContentHandler(mStringHandler);
								msXmlReader.parse(mInputSource);

								mStringList = mStringHandler.getParsedData();
								Log.d("mStringList", mStringList.size() + "");
								// endDate = new Date();
								// Log.e("得到list",
								// (endDate.getTime() - beginDate
								// .getTime()) / 1000 + "S");

							} catch (Exception e) {
								e.toString();
							}

						} else {
							Log.d("kmvc", "没读取到数据");
							progress.dismiss();
						}
					}

				} catch (Exception e) {
					progress.dismiss();
				}
				h.post(r);
			}
		}.start();

	}

}
